import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from 'vuex-persistedstate';
import {
  uniStorage
} from './utils';

Vue.use(Vuex);

var defaultStore = new Vuex.Store({
  plugins: [
    createPersistedState({
      paths: [
        'system.ttkn2',
        'system.jmaKey',
        'system.userInfo',
      ],
      storage: uniStorage(),
      // reducer(state) {
      //   return {
      //     'system': {
      //       'hasKey': state.system.hasKey // 只持久化 user.token
      //     }
      //   };
      // }
    })
  ],
  strict: process.env.NODE_ENV !== 'production',
  state: {},
  getters: {
    // 通用 getter，支持模块路径
    getState: (state, getters, rootState) => (path) => {
      const paths = path.split('/'); // 解析路径
      let currentState = rootState;
      for (const key of paths) {
        if (currentState[key] !== undefined) {
          currentState = currentState[key];
        } else {
          return undefined; // 如果路径不存在，返回 undefined
        }
      }
      return currentState;
    }
  },
  mutations: {
    // 通用 setState 方法
    setState(state, payload) {
      const {
        path,
        data
      } = payload; // path 是模块路径，data 是要更新的数据
      const paths = path.split('/'); // 将路径拆分为数组
      let currentState = state;

      // 遍历路径，动态访问状态
      for (let i = 0; i < paths.length - 1; i++) {
        if (currentState[paths[i]] !== undefined) {
          currentState = currentState[paths[i]];
        } else {
          Vue.set(currentState, paths[i], {}); // 如果路径不存在，自动创建
          currentState = currentState[paths[i]];
        }
      }

      // 更新最终的状态
      const finalKey = paths[paths.length - 1];
      Vue.set(currentState, finalKey, data); // 确保响应性
    }
  },
  actions: {},
});

var store;

function createInstance(Vue, options) {
  if (store) {
    return store;
  }
  if (options?.default && options.default instanceof Vuex.Store) {
    store = options.default
  } else {
    store = defaultStore;
  }

  (options?.modules || []).forEach(name => {
    let storeModule;
    try {
      storeModule = require(`@/common/stores/modules/${name}.js`);
    } catch (e) {
      storeModule = require(`../stores/modules/${name}.js`);
    }
    if (storeModule) {
      store.registerModule(name, storeModule);
    } else {
      throw new Error('store module error');
    }
  });

  return store;
}

export {
  createInstance
};
export default store